﻿using MvcWechat.Common;
using MvcWechat.ServiceReference1;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;

namespace MvcWechat.Controllers
{
    public class CustomerController : BaseController
    {
        private static RetailClient service = new RetailClient();
        // method start 
        /////////////////////////////////////////////////页面和方法分割线/////////////////////////////////////////////////////////////////////////////////////

        //绑定
        public JsonResult BindOnAccount(string param)
        {
            return Json(service.BindOnAccount(GetInputJson()),JsonRequestBehavior.AllowGet);
        }
        public JsonResult CustomerRegister(string param)
        {
            return Json(service.Register(GetInputJson()), JsonRequestBehavior.AllowGet);
        }
        public JsonResult IsNoRegister(string param)
        { 
            return Json(service.IsNoRegister(GetInputJson()), JsonRequestBehavior.AllowGet);
        }
        //获取验证码
        public JsonResult ValidateCode(string param)
        { 
            return Json(service.ValidateCode(GetInputJson()), JsonRequestBehavior.AllowGet);
        }
        //获取验证码
        public JsonResult CustomerRegIsExist(string param)
        {
            return Json(service.CustomerRegIsExist(GetInputJson()), JsonRequestBehavior.AllowGet);
        }


        /// <summary>
        /// 登录
        /// </summary>
        /// <returns></returns>
        public JsonResult CustomerLogin()
        {
            string msgInfo = "{\"msgcode\":#code,\"msginfo\":#msg,\"data\":#result}"; //templateJSON

            string customerLoginJson = GetInputJson();

            try
            {
                Dictionary<string, string> dictCust = JsonConvert.DeserializeObject<Dictionary<string, string>>(customerLoginJson);
                dictCust.Add("ActiveIP", HttpContext.Request.UserHostAddress);
                string customerLoginResult = string.Empty;
                var msginfo = "msginfo";
                if (dictCust.ContainsKey("Name") && dictCust.ContainsKey("Pwd"))
                {
                    msginfo = "data"; 
                      customerLoginResult = service.CustomerLogin(JsonConvert.SerializeObject(dictCust)).Replace("\"msginfo\":","\"data\":"); 
                } 
 
                else
                {
                    string jsonparam = JsonConvert.SerializeObject(dictCust);
                    customerLoginResult = service.CustomerLoginAndRegister(jsonparam);
                }
                Dictionary<string, object> param = ManagerJson.Deserialize<Dictionary<string, object>>(customerLoginResult); //Json转字典  

                //登录成功,建立缓存
 
                if (param.ContainsKey("msgcode") && param["msgcode"].ToString().ToLower() != "false") 
                {
                    Dictionary<string, object> customerParam = ManagerJson.Deserialize<Dictionary<string, object>>(param[msginfo].ToString());
                    ManagerSession.SetSession("CustomerID", customerParam["CustomerID"]);
                    ManagerSession.SetSession("CustomerName", customerParam["UserName"]);
                    ManagerSession.SetSession("Discounts", customerParam["Discounts"]);//用户折扣优惠 
                }

                return Json(customerLoginResult);//Wcf的CustomerLogin方法
            }
            catch (Exception ex)
            {
                return Json(msgInfo.Replace("#code", "false").Replace("#msg", ManagerJson.Serialize(ex.Message)).Replace("#result", ManagerJson.Serialize("")));
            }
        }

         
            /// <summary>
            /// 退出登录
            /// </summary>
            /// <returns></returns>
            public JsonResult Logout()
        {
            try
            {
                //清除Session
                ManagerSession.RemoveSession("CustomerID");
                ManagerSession.RemoveSession("CustomerName"); 
                ManagerSession.RemoveSession("Discounts");//用户折扣优惠 
                return Json(true);
            }
            catch (Exception)
            {
                return Json(false);
            }
        }
        /// <summary>
        /// 客户资料
        /// </summary>
        /// <returns></returns>
        public JsonResult GetCustomerInfo()
        { 
            string getCustomerInfoJson = GetInputJson();
            return Json(service.GetCustomerInfo(getCustomerInfoJson));
        }
        /// <summary>
        /// 修改密码
        /// </summary>
        /// <returns></returns>
        public JsonResult CustomerModifyPassword()
        {
            string customerModifyPasswordJson = GetInputJson();
            return Json(service.CustomerModifyPassword(customerModifyPasswordJson));
        }
        /// <summary>
        /// 修改客户资料
        /// </summary>
        /// <returns></returns>
        public JsonResult EditCustomer()
        {
            string editCustomerJson = GetInputJson();
            return Json(service.EditCustomer(editCustomerJson));
        }
        /// <summary>
        /// 一级下二级的单
        /// </summary>
        /// <returns></returns>
        public JsonResult SubmitOrder()
        {
            //对应一级过来的单
            //CustomerID = customerId, OrderType = 1, InventoryIDs = item.InventoryIDs, Remarks = item.Remarks

            var param = GetInputDict(); 
            List<dynamic> dynamics = new List<dynamic>();
            dynamics.Add(new { GoodsTypeID = param["OrderType"].ToString(), InventoryIDs = param["InventoryIDs"].ToString().Split(',').Select(Int32.Parse).ToArray() });
            param["InventoryList"] = dynamics;
            param["ParentKey"] = CommonPage.GetConfigSettings().ParentKey; //需要传一个key过去，不然报错 
            var requestParam = JsonConvert.SerializeObject(param);
            var result = service.SubmitOrders(requestParam, "yiji_Api"); //yiji_Api这个标识改动的话Retail.svc.cs里面 isOpenInterface=="yiji_Api" 也要改动
            return Json(result);

        }

    }
}
